//
//  UIWindow_public extension.swift
//  MyLibrary
//
//  Created by 周博 on 2020/7/7.
//  Copyright © 2020 ncit. All rights reserved.
//

import UIKit


public extension UIWindow {

    /** 获取当前window的最上层控制器 */
    func topViewController() -> UIViewController? {
        guard var rootViewController = self.rootViewController else {
            return nil
        }
        while (rootViewController.presentedViewController != nil) {
            rootViewController = rootViewController.presentedViewController!
        }
        return topViewController(for: rootViewController)
    }

    private func topViewController(for rootViewController: UIViewController?) -> UIViewController? {
        guard let rootViewController = rootViewController else {
            return nil
        }

        switch rootViewController {
        case is UINavigationController:
            let navigationController = rootViewController as! UINavigationController
            return topViewController(for: navigationController.viewControllers.last)
        case is UITabBarController:
            let tabBarController = rootViewController as! UITabBarController
            return topViewController(for: tabBarController.selectedViewController)
        default:
            return rootViewController
        }
    }
}
